using System;
using System.Windows.Forms;
using System.Drawing;
using System.Data;
using MySql.Data.MySqlClient;
using ScottPlot;
using ScottPlot.WinForms;
using System.Threading.Tasks;
using System.Text;
using System.Net.Http;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using RestSharp;

namespace Weather
{
    public partial class MoodAnalysisForm : Form
    {
        private FormsPlot formsPlot; // 绘制图标
        private ComboBox cmbAnalysisType; // 选择分析类型
        private DateTimePicker dtpStartDate; // 开始时间
        private DateTimePicker dtpEndDate;  // 结束时间
        private RichTextBox txtAIReport; // ai生成报告
        private Button btnGenerateReport; // 生成报告按钮
        private Panel reportPanel; // 报告相关面板

        public MoodAnalysisForm()
        {
            InitializeComponents();
            LoadAnalysis();
        }

        private void InitializeComponents()
        {
            this.BackColor = Color.White;
            this.Dock = DockStyle.Fill;

            // 分析类型选择
            cmbAnalysisType = new ComboBox
            {
                Location = new Point(20, 20),
                Size = new Size(150, 30),
                DropDownStyle = ComboBoxStyle.DropDownList,
                Font = new Font("Microsoft YaHei", 10)
            };
            cmbAnalysisType.Items.AddRange(new string[] { 
                "心情趋势", 
                "天气影响",
                "AI分析报告"  
            });
            cmbAnalysisType.SelectedIndex = 0;
            cmbAnalysisType.SelectedIndexChanged += (s, e) => LoadAnalysis();

            // 日期选择
            var lblDateRange = new Label
            {
                Text = "日期范围：",
                Location = new Point(190, 23),
                Size = new Size(80, 30),
                Font = new Font("Microsoft YaHei", 10)
            };
           
            dtpStartDate = new DateTimePicker
            {
                Location = new Point(270, 20),
                Size = new Size(120, 30),
                Format = DateTimePickerFormat.Short,
                Value = DateTime.Now.AddMonths(-1)
            };

            dtpEndDate = new DateTimePicker
            {
                Location = new Point(400, 20),
                Size = new Size(120, 30),
                Format = DateTimePickerFormat.Short,
                Value = DateTime.Now
            };

            dtpStartDate.ValueChanged += (s, e) => LoadAnalysis();
            dtpEndDate.ValueChanged += (s, e) => LoadAnalysis();

            // 绘制图标
            formsPlot = new FormsPlot
            {
                Location = new Point(20, 60),
                Size = new Size(700, 400),
                BackColor = Color.White
            };

            // 添加报告面板
            reportPanel = new Panel
            {
                Location = new Point(20, 60),
                Size = new Size(700, 400),
                BackColor = Color.White,
                Visible = false
            };

            txtAIReport = new RichTextBox
            {
                Dock = DockStyle.Fill,
                ReadOnly = true,
                Font = new Font("Microsoft YaHei", 10),
                BackColor = Color.White
            };

            btnGenerateReport = new Button
            {
                Text = "生成分析报告",
                Dock = DockStyle.Bottom,
                Height = 40,
                BackColor = Color.FromArgb(72, 190, 117),
                ForeColor = Color.White,
                FlatStyle = FlatStyle.Flat
            };
            btnGenerateReport.Click += async (s, e) => await GenerateAIReport();

            reportPanel.Controls.AddRange(new Control[] { txtAIReport, btnGenerateReport });
            this.Controls.Add(reportPanel);

            this.Controls.AddRange(new Control[] { 
                cmbAnalysisType, lblDateRange, 
                dtpStartDate, dtpEndDate, formsPlot 
            });
        }

        private void LoadAnalysis()
        {
            try
            {
                // 隐藏所有面板
                formsPlot.Visible = false;
                reportPanel.Visible = false;

                switch (cmbAnalysisType.SelectedIndex)
                {
                    case 0:
                        formsPlot.Visible = true;
                        LoadMoodTrend();
                        break;
                    case 1:
                        formsPlot.Visible = true;
                        LoadWeatherImpact();
                        break;
                    case 2:
                        reportPanel.Visible = true;
                        break;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载分析数据失败：{ex.Message}");
            }
        }

        // 心情趋势
        private void LoadMoodTrend()
        {
            try
            {
                string sql = @"SELECT 
                                DATE(created_at) as date,
                                AVG(mood_score) as avg_score
                              FROM user_moods 
                              WHERE user_id = @userId
                                AND created_at BETWEEN @startDate AND @endDate
                              GROUP BY DATE(created_at)
                              ORDER BY date";

                var parameters = new MySqlParameter[]
                {
                    new MySqlParameter("@userId", MySqlDbType.Int32) { Value = CurrentUser.Id },
                    new MySqlParameter("@startDate", MySqlDbType.DateTime) { Value = dtpStartDate.Value },
                    new MySqlParameter("@endDate", MySqlDbType.DateTime) { Value = dtpEndDate.Value }
                };

                var dt = DBHelper.ExecuteQuery(sql, parameters);

                if (dt.Rows.Count == 0)
                {
                    formsPlot.Plot.Clear();
                    formsPlot.Plot.Title("暂无数据");
                    formsPlot.Refresh();
                    return;
                }

                var dates = new List<DateTime>();
                var scores = new List<double>();

                foreach (DataRow row in dt.Rows)
                {
                    dates.Add((DateTime)row["date"]);
                    scores.Add(Convert.ToDouble(row["avg_score"]));
                }

                formsPlot.Plot.Clear();

                // 心情分数折线图
                var scatter = formsPlot.Plot.AddScatter(
                    dates.Select(x => x.ToOADate()).ToArray(), // 转换日期格式，再转换为数组
                    scores.ToArray(),
                    Color.FromArgb(72, 190, 117),
                    label: "平均心情");
                scatter.MarkerSize = 10;

                formsPlot.Plot.XAxis.DateTimeFormat(true);
                formsPlot.Plot.Title("心情趋势分析");
                formsPlot.Plot.YAxis.Label("心情评分");
                formsPlot.Plot.SetAxisLimits(yMin: 0, yMax: 5);
                formsPlot.Plot.Legend(location: ScottPlot.Alignment.UpperRight);
                formsPlot.Refresh();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载趋势数据失败：{ex.Message}");
            }
        }

        // 天气影响
        private void LoadWeatherImpact()
        {
            string sql = @"SELECT 
                            weather,
                            AVG(mood_score) as avg_score,
                            COUNT(*) as count
                          FROM user_moods 
                          WHERE user_id = @userId
                            AND created_at BETWEEN @startDate AND @endDate
                          GROUP BY weather
                          HAVING count > 0
                          ORDER BY avg_score DESC";

            var parameters = new MySqlParameter[]
            {
                new MySqlParameter("@userId", MySqlDbType.Int32) { Value = CurrentUser.Id },
                new MySqlParameter("@startDate", MySqlDbType.DateTime) { Value = dtpStartDate.Value },
                new MySqlParameter("@endDate", MySqlDbType.DateTime) { Value = dtpEndDate.Value }
            };

            var dt = DBHelper.ExecuteQuery(sql, parameters);

            var weathers = new List<string>();
            var scores = new List<double>();

            foreach (DataRow row in dt.Rows)
            {
                weathers.Add(row["weather"].ToString());  // 只显示天气类型
                scores.Add(Convert.ToDouble(row["avg_score"]));
            }

            formsPlot.Plot.Clear();
            var bar = formsPlot.Plot.AddBar(scores.ToArray());
            bar.FillColor = Color.FromArgb(72, 190, 117);

            formsPlot.Plot.XTicks(
                Enumerable.Range(0, weathers.Count).Select(x => (double)x).ToArray(), 
                weathers.ToArray());
            formsPlot.Plot.Title("天气对心情的影响");
            formsPlot.Plot.YAxis.Label("平均心情评分");
            formsPlot.Plot.XAxis.Label("天气类型");  // 修改标签
            formsPlot.Plot.SetAxisLimits(yMin: 0, yMax: 5);
            formsPlot.Plot.XAxis.TickLabelStyle(rotation: 45);
            formsPlot.Refresh();
        }

        // ai分析报告
        private async Task GenerateAIReport()
        {
            try
            {
                btnGenerateReport.Enabled = false;
                btnGenerateReport.Text = "正在生成报告...";
                txtAIReport.Text = "正在收集数据并生成报告，请稍候...";

                // 收集数据
                var data = await CollectUserData();
                
                // 生成提示词
                string prompt = GeneratePrompt(data);

                // 调用AI API
                string report = await CallAIAPI(prompt);

                // 显示报告
                txtAIReport.Text = report;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"生成报告失败：{ex.Message}");
            }
            finally
            {
                btnGenerateReport.Enabled = true;
                btnGenerateReport.Text = "生成分析报告";
            }
        }

        private async Task<Dictionary<string, object>> CollectUserData()
        {
            var data = new Dictionary<string, object>();

            // 1. 基础统计
            string sql = @"
                SELECT 
                    COUNT(*) as total_records,
                    AVG(mood_score) as avg_score,
                    (
                        SELECT mood_type 
                        FROM user_moods m2 
                        WHERE m2.user_id = @userId 
                        AND m2.created_at BETWEEN @startDate AND @endDate
                        GROUP BY mood_type 
                        ORDER BY COUNT(*) DESC 
                        LIMIT 1
                    ) as most_mood
                FROM user_moods m1
                WHERE user_id = @userId 
                AND created_at BETWEEN @startDate AND @endDate";

            var parameters = new MySqlParameter[]
            {
                new MySqlParameter("@userId", MySqlDbType.Int32) { Value = CurrentUser.Id },
                new MySqlParameter("@startDate", MySqlDbType.DateTime) { Value = dtpStartDate.Value },
                new MySqlParameter("@endDate", MySqlDbType.DateTime) { Value = dtpEndDate.Value }
            };

            var dt = DBHelper.ExecuteQuery(sql, parameters);
            if (dt.Rows.Count > 0)
            {
                data["总记录数"] = dt.Rows[0]["total_records"];
                data["平均心情分"] = Math.Round(Convert.ToDouble(dt.Rows[0]["avg_score"]), 2);
                data["最常见心情"] = dt.Rows[0]["most_mood"] ?? "暂无数据";
            }

            // 2. 天气影响
            sql = @"
                SELECT weather, AVG(mood_score) as avg_score
                FROM user_moods 
                WHERE user_id = @userId 
                AND created_at BETWEEN @startDate AND @endDate
                GROUP BY weather
                ORDER BY avg_score DESC
                LIMIT 1";

            dt = DBHelper.ExecuteQuery(sql, parameters);
            if (dt.Rows.Count > 0)
            {
                data["最佳天气"] = $"{dt.Rows[0]["weather"]} (平均{Math.Round(Convert.ToDouble(dt.Rows[0]["avg_score"]), 2)}分)";
            }

            return data;
        }

        // 语言格式
        private string GeneratePrompt(Dictionary<string, object> data)
        {
            return $@"你是一位专业的心理分析师，请基于以下数据生成一份个性化的心情分析报告：

用户在{dtpStartDate.Value:yyyy年MM月dd日}至{dtpEndDate.Value:yyyy年MM月dd日}期间的心情数据：
- 记录总数：{data["总记录数"]}条
- 平均心情评分：{data["平均心情分"]}/5分
- 最常见心情类型：{data["最常见心情"]}
- 最适合的天气：{data["最佳天气"]}

请从以下几个方面进行分析：
1. 总体心情状况评估
2. 情绪波动规律分析
3. 天气对心情的影响分析
4. 个性化建议和改善方案
5. 积极因素识别和强化建议

要求：
1. 使用温暖、积极但专业的语气
2. 给出具体可行的建议
3. 重点关注用户的积极情绪和成长潜力
4. 适当引用心理学理论支持分析结论

请生成一份结构清晰、内容专业的分析报告。";
        }

        // 鉴权api
        private async Task<string> GetBaiduAccessToken()
        {
            try
            {
                var client = new RestClient("https://aip.baidubce.com/oauth/2.0/token");
                client.Timeout = -1;
                var request = new RestRequest(Method.POST);
                
                // 使用 AddParameter 而不是 AddHeader
                request.AddParameter("grant_type", "client_credentials");
                request.AddParameter("client_id", AppConfig.BaiduApiKey);
                request.AddParameter("client_secret", AppConfig.BaiduSecretKey);
                
                var response = await client.ExecuteAsync(request);
                Console.WriteLine($"Token Response: {response.Content}");
                
                var result = JsonConvert.DeserializeObject<dynamic>(response.Content);
                return result.access_token.ToString();
            }
            catch (Exception ex)
            {
                throw new Exception($"获取百度Access Token失败：{ex.Message}");
            }
        }

        // 调用文心一言api
        private async Task<string> CallAIAPI(string prompt)
        {
            try
            {
                string accessToken = await GetBaiduAccessToken();
                // 修改为正确的文心一言接口地址
                var client = new RestClient($"https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/ernie-3.5-128k?access_token={accessToken}");
                client.Timeout = -1;
                
                var request = new RestRequest(Method.POST);
                request.AddHeader("Content-Type", "application/json");
                
                var requestBody = new
                {
                    messages = new[]
                    {
                        new { role = "user", content = prompt }
                    }
                };

                request.AddJsonBody(requestBody);

                // 打印请求信息用于调试
                Console.WriteLine($"Request URL: {client.BaseUrl}");
                Console.WriteLine($"Request Body: {JsonConvert.SerializeObject(requestBody)}");

                var response = await client.ExecuteAsync(request);
                Console.WriteLine($"Response Status: {response.StatusCode}");
                Console.WriteLine($"Response Content: {response.Content}");

                var jsonResponse = JObject.Parse(response.Content);
                if (jsonResponse["error_code"] != null)
                {
                    throw new Exception($"API错误：{jsonResponse["error_msg"]}");
                }

                return jsonResponse["result"]?.ToString() 
                    ?? throw new Exception("返回数据格式错误");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"调用AI API失败：{ex.Message}\n请检查API密钥是否正确，网络是否正常。");
                return "生成报告失败，请重试。";
            }
        }
    }
} 